#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
	from xml.etree import ElementTree
except ImportError:
	from elementtree import ElementTree

import gdata.calendar.service
import gdata.service
import atom.service
import gdata.calendar
import atom

import datetime
import dateutil.parser
import traceback


#Import the Base class of all Providers
from gnomeagenda.CalendarProviderBase import CalendarProviderBase
from gettext import gettext as _

from gnomeagenda.appointment import *

class GoogleCalendar(CalendarProviderBase):
	"""Provider for Accessing the google Canendar via the gData API"""
	#set the capability to provider
	capabilities = ['provider']
	def __init__(self):
		"""
		Basic initialization of the Plugin
		you can set the pluginame, author, and a website
		"""
		#Don't forget to Call the CalendarProviderBase 'constructor'
		CalendarProviderBase.__init__(self)
		
		self.Plugin_Name = "Google Calendar"
		self.Plugin_Author = "Florian Dorn"
		
		self.options['username'] = ''
		self.options['password'] = ''
		
	def initPlugin(self, options):
		
		CalendarProviderBase.initPlugin(self,options)
		#initialitze gdata connection
		self.cal_client = gdata.calendar.service.CalendarService()
		self.cal_client.source = 'agenda'
		self.online = False;

		self.cal_client.email = self.options['username']
		self.cal_client.password = self.options['password']	

	def getAllEvents(self,master_update_calendar_flag = False):
		self.notify_query_provider()
		title, start_time, end_time,descr = '','','',''
		__cal = Appointments()
		cals = self.list_calendars()
		for cal in cals:
			self.notify_query_calendar(cal.name)
			update_calendar_flag = master_update_calendar_flag
			if(not update_calendar_flag):
				local_cal = __cal.get_calendar_data(cal['id'])
				if(local_cal != None):
					#print cal['updated_ext']
					#print local2utc(local_cal.updated_ext)		
					update_calendar_flag = (cal['updated_ext'] != local2utc(local_cal.updated_ext))
				else:
					update_calendar_flag = True

			if(update_calendar_flag):
				print "Updating %s,%s" % (cal.name,cal.id)
				projection = 'full'
				#projection = 'free-busy'
				query = gdata.calendar.service.CalendarEventQuery(cal.id, 'private',projection)
				query.start_min = (datetime.datetime.utcnow() + datetime.timedelta(days=-1)) .strftime('%Y-%m-%d')
				query.start_max = (datetime.datetime.utcnow() + datetime.timedelta(days=30)).strftime('%Y-%m-%d')
				query.orderby = 'starttime'
				query.sortorder = 'ascend'
				query.max_results = '48'
				query.singleevents = 'true'
				#print "Adding Calendar: %s" % (a_calendar.title.text)
				try:
					self.queryCalendar(query,cal)
					#only add the calendar all events were properly added 
					self.addCalendar(cal.id,cal.name,cal.color,cal.updated_ext,cal.hidden)
					pass
				except Exception,e:
					print 
					print e
					traceback.print_exc()
					self.notifyError(_("Could not retrieve Calendar '%s'") % cal.name)
	
		return self.update_ok
	def queryCalendar(self,query,cal):
		feed = self.cal_client.CalendarQuery(query)
		cal_name = feed.title.text
		for i, an_event in enumerate(feed.entry):

			#print an_event.eventStatus.value
			#print an_event.title.text
			title = an_event.title.text
			if (title == None):
				title = _("(untitled)")
			for i,a_when in enumerate(an_event.when):
				
				start_time 	= local2utc(convert_datetime(a_when.start_time))
				end_time 	= local2utc(convert_datetime(a_when.end_time))

				place = ""
				for a in an_event.where:
					place = a.value_string
				try:
					descr = ['',an_event.content.text][an_event.content.text != None]
				except:
					descr = ''
				if(an_event.event_status.value != "CANCELED"):
					self.addEvent(an_event.GetHtmlLink().href,cal['id'], start_time, end_time, title, descr,place)
				#else:
				#	print "skipping CANCELED event %s" % an_event.title.text
	def list_calendars(self):
		""" return a list of the calendars """
		
		calendars = []
				##grab all calendars
		try:
			self.cal_client.ProgrammaticLogin()
			feed = self.cal_client.GetCalendarListFeed()
			self.online = True
		except Exception,e:
			self.online = False
			self.notifyError(_("Could not contact the Google Calendar Server:\n%s") % e)
			self.update_ok = False
		
		if(self.online and feed):
			self.update_ok = True
			for i, a_calendar in enumerate(feed.entry):
					hidden = False
					if (a_calendar.hidden.value == "true") or (a_calendar.selected.value == "false"):
						hidden = True
					title = a_calendar.title.text
					color = a_calendar.color.value
					updated = local2utc(convert_datetime(a_calendar.updated.text))
					id = a_calendar.id.text[a_calendar.id.text.rfind('/')+1:].replace('%40','@')

					try:
						calendars.append(Google_Cal(id,title,color,updated,hidden))
					except:
						pass
		return calendars
	def getSettingsPanel(self):
		"""return a gtk Widget showind the settings"""
		return gtk.Label(_("No configuration needed"))
	def applySettings(self):
		"""apply the changes to self.options made to the widgets"""

class Google_Cal(CalCalendar):
	def __init__(self,id,name,color,updated_ext = None,hidden = False):
		CalCalendar.__init__(self,id,name,color,updated_ext,hidden)
